﻿using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Tool.Utils;
using Volo.Abp.DependencyInjection;

namespace Tool.Services
{
    public class InstanceService : IScopedDependency
    {
        private readonly IHttpClientFactory httpClientFactory;

        public InstanceService(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }
        public async Task<List<string>> GetInstances(string clientName, HttpResponseHeaders? httpResponseHeader)
        {
            var instances = new List<string>();

            var query = "/group/user_all_instances/?tag_codes[]=can_read";
            using (var httpClient = httpClientFactory.CreateClient(clientName))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Get, query);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}sqlquery/");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 获取响应头中的 Set-Cookie 字段
                if (httpResponseHeader == null)
                {
                    return instances;
                }
                if (httpResponseHeader.TryGetValues("Set-Cookie", out var cookieValues))
                {
                    foreach (var cookie in cookieValues)
                    {
                        Console.WriteLine("Received Set-Cookie: " + cookie);
                        authRequest.Headers.Add("Cookie", cookie);
                    }
                }

                // 3. 获取 csrftoken（从 Cookie 中）
                // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                if (csrfCookie != null)
                {
                    var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                    if (csrfValue != null)
                    {
                        var token = csrfValue.Substring("csrftoken=".Length);
                        authRequest.Headers.Add("X-CSRFToken", token);
                    }
                }


                var postResponse = await httpClient.SendAsync(authRequest);
                if (postResponse.IsSuccessStatusCode)
                {
                    var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                    var jsonStr = Encoding.UTF8.GetString(responseBody);
                    //jsonStr转换成json对象
                    using (var doc = JsonDocument.Parse(jsonStr))
                    {
                        var root = doc.RootElement;

                        var rows = root.GetProperty("data").EnumerateArray();
                        foreach (JsonElement item in rows)
                        {
                            instances.Add(item.GetProperty("instance_name").ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                    Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                }
            }

            return instances;
        }

        public async Task<List<string>> GetDatabases(string instanceName, string clientName, HttpResponseHeaders? httpResponseHeader)
        {
            var databases = new List<string>();

            var query = $"/instance/instance_resource/?instance_name={instanceName}&resource_type=database";
            using (var httpClient = httpClientFactory.CreateClient(clientName))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Get, query);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}sqlquery/");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 获取响应头中的 Set-Cookie 字段
                if (httpResponseHeader == null)
                {
                    return databases;
                }
                if (httpResponseHeader.TryGetValues("Set-Cookie", out var cookieValues))
                {
                    foreach (var cookie in cookieValues)
                    {
                        Console.WriteLine("Received Set-Cookie: " + cookie);
                        authRequest.Headers.Add("Cookie", cookie);
                    }
                }

                // 3. 获取 csrftoken（从 Cookie 中）
                // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                if (csrfCookie != null)
                {
                    var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                    if (csrfValue != null)
                    {
                        var token = csrfValue.Substring("csrftoken=".Length);
                        authRequest.Headers.Add("X-CSRFToken", token);
                    }
                }


                var postResponse = await httpClient.SendAsync(authRequest);
                if (postResponse.IsSuccessStatusCode)
                {
                    var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                    var jsonStr = Encoding.UTF8.GetString(responseBody);
                    //jsonStr转换成json对象
                    using (var doc = JsonDocument.Parse(jsonStr))
                    {
                        var root = doc.RootElement;

                        var rows = root.GetProperty("data").EnumerateArray();
                        foreach (JsonElement item in rows)
                        {
                            databases.Add(item.ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                    Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                }
            }

            return databases;
        }

        public async Task<List<string>> GetTables(string instanceName, string dbName, string clientName, HttpResponseHeaders? httpResponseHeader)
        {
            var tables = new List<string>();

            var query = $"/instance/instance_resource/?instance_name={instanceName}&db_name={dbName}&resource_type=table";
            using (var httpClient = httpClientFactory.CreateClient(clientName))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Get, query);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}sqlquery/");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 获取响应头中的 Set-Cookie 字段
                if (httpResponseHeader == null)
                {
                    return tables;
                }
                if (httpResponseHeader.TryGetValues("Set-Cookie", out var cookieValues))
                {
                    foreach (var cookie in cookieValues)
                    {
                        Console.WriteLine("Received Set-Cookie: " + cookie);
                        authRequest.Headers.Add("Cookie", cookie);
                    }
                }

                // 3. 获取 csrftoken（从 Cookie 中）
                // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                if (csrfCookie != null)
                {
                    var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                    if (csrfValue != null)
                    {
                        var token = csrfValue.Substring("csrftoken=".Length);
                        authRequest.Headers.Add("X-CSRFToken", token);
                    }
                }


                var postResponse = await httpClient.SendAsync(authRequest);
                if (postResponse.IsSuccessStatusCode)
                {
                    var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                    var jsonStr = Encoding.UTF8.GetString(responseBody);
                    //jsonStr转换成json对象
                    using (var doc = JsonDocument.Parse(jsonStr))
                    {
                        var root = doc.RootElement;

                        var rows = root.GetProperty("data").EnumerateArray();
                        foreach (JsonElement item in rows)
                        {
                            tables.Add(item.ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                    Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                }
            }

            return tables;
        }


        public async Task<string> GetTableStructs(string instanceName, string dbName, string tableName, string clientName, HttpResponseHeaders? httpResponseHeader, List<string> tables)
        {

            var description = string.Empty;
            var query = $"/instance/describetable/";
            using (var httpClient = httpClientFactory.CreateClient(clientName))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Post, query);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}sqlquery/");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 获取响应头中的 Set-Cookie 字段
                if (httpResponseHeader == null)
                {
                    return description;
                }
                if (httpResponseHeader.TryGetValues("Set-Cookie", out var cookieValues))
                {
                    foreach (var cookie in cookieValues)
                    {
                        Console.WriteLine("Received Set-Cookie: " + cookie);
                        authRequest.Headers.Add("Cookie", cookie);
                    }
                }

                // 3. 获取 csrftoken（从 Cookie 中）
                // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                if (csrfCookie != null)
                {
                    var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                    if (csrfValue != null)
                    {
                        var token = csrfValue.Substring("csrftoken=".Length);
                        authRequest.Headers.Add("X-CSRFToken", token);
                    }
                }

                // 构建 Form 数据
                var content = FormHelper.GetTableStructFormData(instanceName, dbName, tableName);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                authRequest.Content = content;
                var postResponse = await httpClient.SendAsync(authRequest);
                if (postResponse.IsSuccessStatusCode)
                {
                    var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                    var jsonStr = Encoding.UTF8.GetString(responseBody);
                    //jsonStr转换成json对象
                    using (var doc = JsonDocument.Parse(jsonStr))
                    {
                        var root = doc.RootElement;

                        var rows = root.GetProperty("data").GetProperty("rows").EnumerateArray();
                        foreach (JsonElement item in rows)
                        {
                            description = item.EnumerateArray().Last().ToString();
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                    Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                }

                httpClient.Dispose();
            }


            return description;

        }
    }
}
